<?php
/**
 * @author yupoxiong<i@yufuping.com>
 */

namespace generate\field;

class SwitchField extends Field
{
    public static $html = <<<EOF
<div class="layui-form-item">
    <label for="[FIELD_NAME]" class="layui-form-label">[FORM_NAME]</label>
    <div class="layui-input-inline">
    <input type="hidden" name="[FIELD_NAME]" id="[FIELD_NAME]" value="{\$data.[FIELD_NAME]|default='[FIELD_DEFAULT]'}">

    <input type="checkbox" lay-skin="switch" lay-text="[ON_TEXT]|[OFF_TEXT]"  value="1" {if(isset(\$data) && \$data.[FIELD_NAME]==1)}checked{/if} lay-filter="[FIELD_NAME]">
    </div>
</div>
<script>
layui.use('form', function () {
    var form = layui.form;
    form.on('switch([FIELD_NAME])', function () {
        console.log(this.checked);
        if(this.checked){
            $('#[FIELD_NAME]').val('1');
        }else{
            $('#[FIELD_NAME]').val('0');
        }
    });
})
</script>
\n

EOF;

    public static $rules = [
        'required'   => '非空',
        'regular'    => '自定义正则'
    ];


    public static function create($data)
    {
        $html = self::$html;
        //switch开的文字
        if (isset($data['on_text'])) {
            $html = str_replace('[ON_TEXT]', $data['on_text'], $html);
        } else {
            $html = str_replace('[ON_TEXT]', '是', $html);
        }
        //switch关的文字
        if (isset($data['off_text'])) {
            $html = str_replace('[OFF_TEXT]', $data['off_text'], $html);
        } else {
            $html = str_replace('[OFF_TEXT]', '否', $html);
        }

        return str_replace(array('[FORM_NAME]', '[FIELD_NAME]', '[FIELD_DEFAULT]'), array($data['form_name'], $data['field_name'], $data['field_default']), $html);
    }
}